package com.ctcemti.mdm.project.sys.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.ctcemti.mdm.common.exception.InvalidParamException;
import com.ctcemti.mdm.common.util.*;
import com.ctcemti.mdm.project.common.excelverifyhandler.ExcelVerifyHandlerForResMaterialLibrary;
import com.ctcemti.mdm.project.sys.dao.ResMaterialLibraryMapper;
import com.ctcemti.mdm.project.sys.entity.ResMaterialLibrary;
import com.ctcemti.mdm.project.sys.service.IResMaterialLibraryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@Service
@Slf4j
public class ResMaterialLibraryServiceImpl implements IResMaterialLibraryService {

    @Value("${ctcemti.errorfilepath}")
    private String errorfilepath;

    @Autowired
    private ResMaterialLibraryMapper resMaterialLibraryMapper;


    @Transactional
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return resMaterialLibraryMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    @Override
    public int insert(ResMaterialLibrary record) {
        return resMaterialLibraryMapper.insert(record);
    }

    @Transactional
    @Override
    public int insertSelective(ResMaterialLibrary record) {
        return resMaterialLibraryMapper.insertSelective(record);
    }

    @Override
    public ResMaterialLibrary selectByPrimaryKey(Integer id) {
        return resMaterialLibraryMapper.selectByPrimaryKey(id);
    }

    @Transactional
    @Override
    public int updateByIdSelective(ResMaterialLibrary record) {
        return resMaterialLibraryMapper.updateByIdSelective(record);
    }

    @Transactional
    @Override
    public int updateByPrimaryKey(ResMaterialLibrary record) {
        return resMaterialLibraryMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<ResMaterialLibrary> selectAllResMaterialLibrary() {
        return resMaterialLibraryMapper.selectAll();
    }

    @Override
    public List<ResMaterialLibrary> selectByPid(String s) {
        Example example = new Example(ResMaterialLibrary.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("pid",s);
        return resMaterialLibraryMapper.selectByExample(example);
    }

    @Override
    public List<ResMaterialLibrary> selectResMaterialLibrary(ResMaterialLibrary ResMaterialLibrary) {
        return resMaterialLibraryMapper.select(ResMaterialLibrary);
    }

    @Transactional
    @Override
    public int deleteByPrimaryKeys(String ids) {
        return resMaterialLibraryMapper.deleteByIds(ids);
    }

    @Override
    public PageInfo<ResMaterialLibrary> selectListByPid(ResMaterialLibrary resMaterialLibrary) {
        PageHelper.startPage(resMaterialLibrary.getPageIndex(),resMaterialLibrary.getPageSize(),"code");
        Example example = new Example(ResMaterialLibrary.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("category",resMaterialLibrary.getCategory());
        if(!StringUtils.isNullOrEmpty(resMaterialLibrary.getName())){
            criteria.andLike("name","%"+resMaterialLibrary.getName()+"%");
        }
        if(!StringUtils.isNullOrEmpty(resMaterialLibrary.getName())){
            criteria.andLike("code","%"+resMaterialLibrary.getCode()+"%");
        }
        if(!StringUtils.isNullOrEmpty(resMaterialLibrary.getName())){
            criteria.andLike("Specs","%"+resMaterialLibrary.getSpecs()+"%");
        }
        List<ResMaterialLibrary> list = resMaterialLibraryMapper.selectByExample(example);
        PageInfo<ResMaterialLibrary> pageInfo =  new PageInfo<ResMaterialLibrary>(list);
        return pageInfo;
    }

    @Transactional
    @Override
    public Map<String, Object> uploadFile(MultipartFile multipartFile, String category, HttpServletResponse response, HttpServletRequest request) throws SQLException, IOException, InvalidParamException {
        if(StringUtils.isNullOrEmpty(category)){
            throw new InvalidParamException("物资分类不能为空!");
        }
        Map<String,Object> resultMap = new HashMap<String,Object>();
        ExcelImportResult<ResMaterialLibrary> excelImportResult = ExcelParseUtils.importExcelMore(multipartFile,0,1,ResMaterialLibrary.class,new ExcelVerifyHandlerForResMaterialLibrary(resMaterialLibraryMapper));
        boolean flag = true;
        if(excelImportResult == null){
            resultMap.put("flag",flag);
        }else if(excelImportResult.getFailList().size()>0){//验证失败，重新写入excel，并保存
            String filename = UUID.randomUUID().toString();//获取新的文件名
            File folder = new File(errorfilepath);//文件夹
            if(!folder.exists()){
                boolean mkFlag = folder.mkdirs();
                if (mkFlag) {
                    log.error("未找到上传文件夹，新建文件夹");
                }
            }
            FileOutputStream fos = null;
            try {
                //fileOutputStream = new FileOutputStream(file);
                //excelImportResult.getWorkbook().write(fileOutputStream);
                List<ResMaterialLibrary> slist = excelImportResult.getList();//获取所有成功项
                List<ResMaterialLibrary> flist = excelImportResult.getFailList();//获取所有失败项
                slist.addAll(flist);
                Collections.sort(slist);
                ExportParams exportParams = new ExportParams(null,null,"错误列表");
                exportParams.setStyle(ExcelExportStylerImpl.class);
                Workbook workbook = ExcelExportUtil.exportExcel(exportParams,ResMaterialLibrary.class, slist);
                fos = new FileOutputStream(errorfilepath+"/"+filename+".xls");
                workbook.write(fos);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    fos.close();
                }
            }
            flag = false;
            resultMap.put("flag",flag);
            resultMap.put("filecode",filename);
        }else{//成功验证，准备导入数据
            List<ResMaterialLibrary> list = excelImportResult.getList();
            String loginId = JWTUtil.getLoginId(request.getHeader("Authorization"));
            for(ResMaterialLibrary resMaterialLibrary:list){
                resMaterialLibrary.setCreator(loginId);//添加导入人
                resMaterialLibrary.setCategory(category);
            }
            //物资字典库批量插入
            BatchOperationUtils<ResMaterialLibrary> batchOperationUtils = new BatchOperationUtils();
            batchOperationUtils.batchOperation(list, 200,var->resMaterialLibraryMapper.insertBatch(var));

            resultMap.put("flag",flag);
        }
        return resultMap;
    }
}
